package com.google.code.ptrends.catparsers.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.google.code.ptrends.catparsers.AbstractCategoryParser;

/**
 * Utility class for usage inside {@link AbstractCategoryParser} concrete
 * implementations.
 * 
 * @author ternovykh
 * 
 */
public final class RegexHelper {

	private RegexHelper() {
	}

	/**
	 * Reads regular expression string pattern using it's text key from
	 * predefined location in resources
	 * 
	 * @param key
	 *            Text key of regular expression
	 * @return String pattern of regular expression (if exists) using provided
	 *         key or null in there is no such a pattern with given key
	 */
	public static String getRegex(final String key) {
		synchronized (locker) {
			if (regexCache == null) {
				regexCache = createCache();
			}
		}
		return regexCache.get(key);
	}

	private static Map<String, String> createCache() {
		final Map<String, String> result = new HashMap<String, String>();
		final File aFile = new File(REGEX_FILE);

		InputStreamReader input = null;
		BufferedReader reader = null;
		try {

			input = new InputStreamReader(new FileInputStream(aFile),
					Charset.forName("UTF-8"));
			reader = new BufferedReader(input);
			try {
				String line = reader.readLine();

				while (line != null) {
					final String[] keyValue = line.split(SPLITTER);
					final String key = keyValue[0];
					final String value = keyValue[1];

					result.put(key, value);

					line = reader.readLine();
				}
			} finally {
				reader.close();
				input.close();
			}
		} catch (IOException e) {
			LOG.error("Error while reading regex", e);
		}

		return result;
	}

	private static Map<String, String> regexCache;
	private static Object locker = new Object();

	private static final String REGEX_FILE = "src/main/resources/com/google/code/ptrends/regular_expressions.txt";
	private static final String SPLITTER = ";;;;;";
	private static final Logger LOG = Logger.getLogger(RegexHelper.class);
}
